package xyz.bali16.module.message.controller;

import com.alibaba.fastjson.JSONObject;
import com.gitee.starblues.bootstrap.annotation.AutowiredType;
import com.gitee.starblues.spring.MainApplicationContext;
import com.gitee.starblues.spring.SpringBeanFactory;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.HtmlUtils;
import xyz.bali16.application.core.model.Result;
import xyz.bali16.application.core.utils.AuthUtils;
import xyz.bali16.application.core.utils.TimeUtil;
import xyz.bali16.application.entity.User;
import xyz.bali16.application.service.UserService;
import xyz.bali16.module.message.entity.Message;
import xyz.bali16.module.message.service.MessageService;

import java.util.*;

import static xyz.bali16.application.core.model.Result.failure;
import static xyz.bali16.application.core.model.Result.success;

/**
 * @author bali2 on 9/3/2023.
 * @version 1.0
 */
@RestController
@RequestMapping(BaseController.API+"message")
@Api(tags = "消息接口")
@AllArgsConstructor

public class MessageController extends BaseController{
    @Autowired
    private MainApplicationContext context;
    @Autowired
    private MessageService messageService;

    // 私信列表
    @RequestMapping(path = "/letter/list", method = RequestMethod.GET)
    public Result<Map<String,Object>> getLetterList(Integer current, Integer size) {
        SpringBeanFactory factory = context.getSpringBeanFactory();
        UserService userService = factory.getBean(UserService.class);
        String username = AuthUtils.getCurrentUsername();
        User user = userService.getByUsername(username);


        // 会话列表
        List<Message> conversationList = messageService.findConversations(
                user.getUserId(), current,size);
        List<Map<String, Object>> conversations = new ArrayList<>();
        if (conversationList != null) {
            for (Message message : conversationList) {
                Map<String, Object> map = new HashMap<>();
                map.put("conversation", message);
                map.put("letterCount", messageService.findLetterCount(message.getConversationId()));
                map.put("unreadCount", messageService.findLetterUnreadCount(user.getUserId(), message.getConversationId()));
                String targetId = user.getUserId().equals(message.getFromId()) ? message.getToId() : message.getFromId();
                map.put("target", userService.getById(targetId));

                conversations.add(map);
            }
        }
        Map<String, Object> ret = new HashMap<>();
        ret.put("conversations", conversations);
        // 查询未读消息数量
        int letterUnreadCount = messageService.findLetterUnreadCount(user.getUserId(), null);
        ret.put("letterUnreadCount", letterUnreadCount);
        return Result.success(ret);
    }

    //私信详细信息
    @RequestMapping(path = "/letter/detail/{conversationId}", method = RequestMethod.GET)
    public Result<Map<String,Object>> getLetterDetail(@PathVariable("conversationId") String conversationId,Integer current, Integer size) {
        SpringBeanFactory factory = context.getSpringBeanFactory();
        UserService userService = factory.getBean(UserService.class);
        // 私信列表
        List<Message> letterList = messageService.findLetters(conversationId, current, size);
        List<Map<String, Object>> letters = new ArrayList<>();
        if (letterList != null) {
            for (Message message : letterList) {
                Map<String, Object> map = new HashMap<>();
                map.put("letter", message);
                map.put("fromUser", userService.getById(message.getFromId()));
                letters.add(map);
            }
        }
        Map<String,Object> ret = new HashMap<>();
        ret.put("letters", letters);
        ret.put("target", getLetterTarget(conversationId));
        List<Long> ids = getLetterIds(letterList);
        if (!ids.isEmpty()) {
            messageService.readMessage(ids);
        }
        return Result.success(ret);
    }

    private User getLetterTarget(String conversationId) {
        SpringBeanFactory factory = context.getSpringBeanFactory();
        UserService userService = factory.getBean(UserService.class);
        String username = AuthUtils.getCurrentUsername();
        User user = userService.getByUsername(username);
        String[] ids = conversationId.split("_");
        String id0 = ids[0];
        String id1 = ids[1];

        if (user.getUserId().equals(id0)) {
            return userService.getById(id1);
        } else {
            return userService.getById(id0);
        }
    }

    //得到未读的id集合
    private List<Long> getLetterIds(List<Message> letterList) {
        SpringBeanFactory factory = context.getSpringBeanFactory();
        UserService userService = factory.getBean(UserService.class);
        String username = AuthUtils.getCurrentUsername();
        User user = userService.getByUsername(username);
        List<Long> ids = new ArrayList<>();

        if (letterList != null) {
            for (Message message : letterList) {
                if (user.getUserId().equals(message.getToId()) && message.getStatus() == 0) {
                    ids.add(message.getId());
                }
            }
        }

        return ids;
    }

    //发私信
    @RequestMapping(path = "/letter/send", method = RequestMethod.POST)
    @ResponseBody
    public Result<String> sendLetter(String toName, String content) {
        SpringBeanFactory factory = context.getSpringBeanFactory();
        UserService userService = factory.getBean(UserService.class);
        String username = AuthUtils.getCurrentUsername();
        User user = userService.getByUsername(username);
        User target = userService.getByUsername(toName);
        if (target == null) {
            return failure("目标用户不存在!");
        }
        Message message = new Message();
        message.setFromId(user.getUserId());
        message.setToId(target.getUserId());
        if (message.getFromId().compareTo(message.getToId())==1) {
            message.setConversationId(message.getFromId() + "_" + message.getToId());
        } else {
            message.setConversationId(message.getToId() + "_" + message.getFromId());
        }
        message.setContent(content);
        message.setGmtCreated(TimeUtil.getNowTimeToMs());
        messageService.addMessage(message);

        return success();
    }



}
